package com.hkjtgc.pcr_app.util

import android.util.Log
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


class RetrofitUtil2 {
    lateinit var retrofit: Retrofit

    companion object {
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            RetrofitUtil2();
        }
    }

    init {
        create()
    }

    class LogInterceptor : Interceptor {
        val tag = "Retrofit"
        override fun intercept(chain: Interceptor.Chain): Response {
            val request = chain.request()
            Log.i(tag, " Request" + request.url + "--" + request.body)
            val response = chain.proceed(request)
            Log.i(tag, "" + response.isSuccessful)
            return response
        }
    }


    private fun create(): Retrofit {
        val builder = OkHttpClient.Builder();
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        val client = builder.addInterceptor(httpLoggingInterceptor)
            .addInterceptor(LogInterceptor())
            .readTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true).build()
        retrofit = Retrofit.Builder().baseUrl("http://192.168.0.210/")
            .addConverterFactory(GsonConverterFactory.create()).client(client).build()
        return retrofit
    }
}
